package test.serverframe.armc.server.manager.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.microcore.entity.AssertCondition;
import com.microcore.service.AssertService;

import test.serverframe.armc.server.manager.controller.vo.InvokeDetailVo;
import test.serverframe.armc.server.manager.dao.mapper.LinkParamMapper;
import test.serverframe.armc.server.manager.dao.mapper.TaskEnterInterfaceMapper;
import test.serverframe.armc.server.manager.dao.mapper.TaskEnterInvokeMapper;
import test.serverframe.armc.server.manager.dao.mapper.TaskMapper;
import test.serverframe.armc.server.manager.domain.LinkParam;
import test.serverframe.armc.server.manager.domain.Task;
import test.serverframe.armc.server.manager.domain.TaskEnterInterface;
import test.serverframe.armc.server.manager.domain.TaskEnterInvoke;
import test.serverframe.armc.server.manager.domain.params.*;
import test.serverframe.armc.server.manager.model.CenterInterface;
import test.serverframe.armc.server.manager.service.ServerApiService;
import test.serverframe.armc.server.manager.service.TaskService;
import test.serverframe.armc.server.util.JsonUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description 服务编排任务接口实现类
 * @Author LSY
 * @Date 2018/9/26 15:56
 * @ClassName test.serverframe.armc.server.manager.service.impl.TaskServiceImpl
 */
@Service("taskService")
public class TaskServiceImpl extends BaseServiceImpl<Task, String> implements TaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private TaskEnterInterfaceMapper taskEnterInterfaceMapper;

    @Autowired
    private LinkParamMapper linkParamMapper;

    @Autowired
    private ServerApiService apiService;
    
    @Autowired
    private TaskEnterInvokeMapper taskEnterInvokeMapper;
    
    @Autowired
    @Qualifier("assertService")
    private AssertService assertService;
    
    private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

    @Override
    protected String getMapperName() {
        return TaskMapper.class.getName();
    }

    /**
     * 新增
     *
     * @param record
     * @return
     */
    @Override
    public int insertSelective(Task record) {
        record.setCreateTime(new Date());
        record.setUpdateTime(new Date());
        return super.insertSelective(record);
    }

    /**
     * 修改
     *
     * @param record
     * @return
     */
    @Transactional
    public int updateSelective(Task record) {
        record.setCreateTime(null);
        record.setUpdateTime(new Date());
        return super.updateByPrimaryKeySelective(record);
    }

    @Override
    @Transactional
    public int addTask(AddAllData addAllData) {
        // 任务信息
        Task task = new Task();
        task.setTaskGroupId(UUID.randomUUID().toString());
        saveTask(addAllData, task);
        return 1;
    }
    
    /**
     * 保存任务
     *
     * @param addAllData
     * @param task
     */
    private void saveTask(AddAllData addAllData, Task task) {
        task.setTaskId(UUID.randomUUID().toString());
        task.setTaskName(addAllData.getTaskName());
        task.setRemark(addAllData.getRemark());
        task.setIsUsed(true);
        task.setVersion(Long.parseLong(format.format(new Date())));
        task.setNodeArr(addAllData.getNodeArr());
        insertSelective(task);
        addAllParam(addAllData, task);
    }

    /**
     * @Descripttion 新增任务关联接口表和参数表
     * @Author LSY  yegui 19/1/10修改
     * @Date 2018/10/7 15:21  
     * @Param [addAllData 自定义数据结构, task 任务实体]
     * @Return
     **/
    public void addAllParam(AddAllData addAllData, Task task) {
    	
    	List<InterfaceData> interfaces = addAllData.getInterfaces();
		for (InterfaceData itfc : interfaces) {
			//任务关联接口数据
			String uuid = UUID.randomUUID().toString();
			TaskEnterInterface taskEnterInterface = new TaskEnterInterface();
	        taskEnterInterface.setTaskEnterId(uuid);
	        taskEnterInterface.setTaskId(task.getTaskId());
	        taskEnterInterface.setNodeId(itfc.getNodeId());
	        taskEnterInterface.setInterfaceId(itfc.getInterfaceId()); //siaid
	        taskEnterInterface.setChildIds(JsonUtil.parseString(itfc.getChildren())); //nodeid
			taskEnterInterface.setParentIds(JsonUtil.parseString(itfc.getParents())); //nodeid
	        taskEnterInterfaceMapper.insertSelective(taskEnterInterface);
			
			 // 参数链路
            ParamsData paramsData = itfc.getParamsData();
            LinkParam linkParam = new LinkParam();
            linkParam.setLinkParamId(UUID.randomUUID().toString());
            linkParam.setInHeader(paramsData.getInHeader());
            linkParam.setInBody(paramsData.getInBody());
            linkParam.setInQuery(paramsData.getInQuery());
            linkParam.setOutValue(paramsData.getOutValue());
            linkParam.setExceptionSign(paramsData.getExceptionSign());
            linkParam.setInterRelateTaskId(taskEnterInterface.getTaskEnterId());
            linkParamMapper.insertSelective(linkParam);
            
            if(itfc.getAssertConditions() != null){
            	   for (AssertCondition assertCondition : itfc.getAssertConditions()) {
                       assertCondition.setAssertId(UUID.randomUUID().toString());
                       assertCondition.setFkId(uuid);
                       if (assertService.isJsonArray(assertCondition.getConditions())) {
                           assertService.addAssert(assertCondition);
                       }
                   }
            }
		}
    }
    
    /**
     * 按时间戳为版本号，新增一个任务
     *
     * @param addAllData
     * @return
     */
    @Override
    @Transactional
    public int updateTask(AddAllData addAllData) {
    	// 任务信息
        Task task = new Task();
        task.setTaskGroupId(addAllData.getTaskGroupId());
        saveTask(addAllData, task);
        //更新添加关联关系
        /*List<TaskEnterInvoke> teiList = taskEnterInvokeMapper.selectByTaskId(addAllData.getTaskId());
        if (teiList != null && teiList.size() > 0) {
        	addTaskEnterInvoke(task.getTaskId(), teiList);
        }*/
        //删除接口关联任务关系
        //deleteTaskRelateInterface(addAllData);
        //直接新增任务关联接口和参数链路（不更新其他任务下的同接口数据），保留原有的历史数据供其他的任务使用
        
        return 1;
    }

	/*
	 * @author yegui  
	 * @date 2018年12月20日  
	 * void
	 */  
	/*private void addTaskEnterInvoke(String taskId, List<TaskEnterInvoke> teiList) {
		//List<TaskEnterInvoke> teiList = taskEnterInvokeMapper.selectByTaskId(addAllData.getTaskId());
		List<TaskEnterInvoke> newTeiList = new ArrayList<>();
		for (TaskEnterInvoke tei : teiList) {
			TaskEnterInvoke newTei = new TaskEnterInvoke();
			newTei.setTaskId(taskId);
			newTei.setTaskDelay(tei.getTaskDelay());
			newTei.setTaskEnterInvokeId(UUID.randomUUID().toString());
			newTei.setTaskInvokeId(tei.getTaskInvokeId());
			newTei.setTaskParentIds(tei.getTaskParentIds());
			newTei.setTaskChildIds(tei.getTaskChildIds());
			//newTei.setTaskOrder(tei.getTaskOrder());
			newTeiList.add(newTei);
		}
		taskEnterInvokeMapper.insertCollectList(newTeiList);
	}*/

    @Override
    public AddAllData findTask(String taskId) throws Exception {
        if (StringUtils.isEmpty(taskId)) {
            throw new Exception("任务id为空！");
        }
        Task task = taskMapper.selectByPrimaryKey(taskId);
      
        //自定义接口信息
        AddAllData addAllData = new AddAllData();
        addAllData.setTaskName(task.getTaskName());
        addAllData.setRemark(task.getRemark());
        addAllData.setTaskGroupId(task.getTaskGroupId());
        addAllData.setTaskId(taskId);
        addAllData.setNodeArr(task.getNodeArr());
        
        
        List<InterfaceData> interfaces = new ArrayList<>();
        List<TaskEnterInterface> taskEnterInterface = taskEnterInterfaceMapper.selectByTaskIds(taskId);
        for (TaskEnterInterface tei : taskEnterInterface) {
        	LinkParam linkParam = linkParamMapper.selectByInterRelateTaskId(tei.getTaskEnterId());
        	InterfaceData data = new InterfaceData();
        	ParamsData paramsData = new ParamsData();
        	CenterInterface centerInterface = apiService.getInterface(tei.getInterfaceId());
        	data.setInterfaceId(centerInterface.getSiaId());
        	data.setInterfaceName(centerInterface.getSiaName());
        	
        	paramsData.setExceptionSign(linkParam.getExceptionSign());
        	paramsData.setInBody(linkParam.getInBody());
        	paramsData.setInHeader(linkParam.getInHeader());
        	paramsData.setInQuery(linkParam.getInQuery());
        	paramsData.setOutValue(linkParam.getOutValue());
        	data.setParamsData(paramsData);
        	interfaces.add(data);
        }
        addAllData.setInterfaces(interfaces);
        return addAllData;
        
    }

	/*
     * 根据taskId查询
     */
    @Override
    public Task selectByPrimaryKey(String taskId) {
    	return super.selectByPrimaryKey(taskId);
    }

	@Override
	public List<InvokeDetailVo> findTaskByTaskInvokeId(String taskInvokeId) {
		return taskMapper.findTaskByTaskInvokeId(taskInvokeId);
	}

	
	@Override
	public List<String> findTaskName() {
		return taskMapper.findTaskName();
	}
	
    /*private void deleteTaskRelateInterface(AddAllData addAllData) {
	List<TaskEnterInterface> teis = taskEnterInterfaceMapper.selectByTaskIds(addAllData.getTaskId());
	//删除所有关联关系
	taskEnterInterfaceMapper.deletebyTaskId(addAllData.getTaskId());
	for (TaskEnterInterface tei : teis) {
		linkParamMapper.deleteByNodeId(tei.getNodeId());
	}
}*/
}
